#include "music.h"
#include "ui_music.h"
#include"customdelegete.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonParseError>
#include <QNetworkReply>
#include <QNetworkRequest>
#include<QVariant>
#include <QtMultimedia/QMediaPlayer>
#include<QListWidgetItem>
#include <QTcpSocket>
#include <QTcpSocket>
#include"comment.h"
#include "mainwindow.h"
#include"mainwindow.h"
#include "ui_mainwindow.h"

music::music(QTcpSocket * clientSocket, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::music)
{
    ui->setupUi(this);


//    this->setWindowFlag(Qt::FramelessWindowHint);//去掉边框
//    this->setAttribute(Qt::WA_TranslucentBackground);//窗口透明化
    //按钮圆形化
    ui->pushButton_2->setStyleSheet("border-image: url(:/上一首.png); border:3px solid black; border-radius: 50px; ");
    ui->pushButton_3->setStyleSheet("border-image: url(:/暂停.png); border:3px solid black; border-radius: 50px; ");
    ui->pushButton_4->setStyleSheet("border-image: url(:/下一首.png); border:3px solid black; border-radius: 50px; ");

    this->clientSocket = clientSocket;
    //隐藏头标签
    ui->tableView->horizontalHeader()->setVisible(false);
    ui->comboBox->addItem("播放模式");
    ui->comboBox->addItem("顺序播放");
    ui->comboBox->addItem("随机播放");
    ui->comboBox->addItem("单曲循环");

    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));

    pModel = new QStandardItemModel(ui->tableView);//实例化模型，并且指定模型依赖的控件
    ui->tableView->setModel(pModel);
    //设置代理类为自己的，进行图像操作
    ui->tableView->setItemDelegateForColumn(4,new customdelegete);//在第4列使用paint画图
//    ui->tableView->setItemDelegateForColumn(5,new customdelegete);
    titles << "歌名" << "歌手" << "专辑" << "时长" <<"喜欢"<<"分类收藏";

    //创建一个新播放列表
    playlist = new QMediaPlaylist;
    //创建一个播放器
    player = new QMediaPlayer;
    player->setPlaylist(playlist);
    playlist->setPlaybackMode(QMediaPlaylist::Loop);
    //把播放器位置改变的信号positionChanged(qint64)，和槽函数slot_positionChanged(qint64)联系起来
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(slot_positionChanged(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(slot_durationChanged(qint64)));

    ui->listWidget->addItems(QStringList()<<"搜索音乐"<<"我喜欢");
    connect(this->clientSocket, &QTcpSocket::readyRead, this, &music::onReadyRead);

//    connect(on_pushButton_3_clicked, &QPushButton::clicked, this, &MusicPlayerWidget::togglePlayPause);
}
void music::paintEvent(QPaintEvent *event)
{
    QPixmap backgroundPixmap;
    backgroundPixmap.load(":/kg_1725158857974.jpg");
    QPainter painter(this);
    // 根据窗口大小调整图片尺寸，保持图片比例
    QPixmap scaledPixmap = backgroundPixmap.scaled(this->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    // 将调整后的图片设置为窗口背景
    painter.drawPixmap(this->rect(), scaledPixmap);
}
music::~music()
{
    delete ui;
}
void music::onReadyRead()
{

    QMSG msg;
        int i=0;
        while (1){
        int ret = clientSocket->read((char*)&msg,sizeof(msg));
        song *s = (song*)msg.buf;
        qDebug()<<msg.type<<" "<<ret<<endl;
        if(msg.type==404)
        {
            break;
        }
        song_List.push_back(*s);


        pModel->setHorizontalHeaderLabels(titles);
        QList<QStandardItem *> sti;


        int m=s->duration2/60;
        int sec=s->duration2%60;
        QString time=QString("%1:%2").arg(m).arg(sec);
        qDebug()<<s->songname<<time<<"i="<<i<<endl;
        sti<< new QStandardItem(s->songname)<< new QStandardItem(s->singer)<< new QStandardItem(s->album_name)<<new QStandardItem(time);
        //构建歌曲播放链接
        QString play_url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(s->music_id);
        pModel->appendRow(sti);
        pModel->setItem(i,4,new QStandardItem("已收藏"));

        playlist->addMedia(QUrl(play_url));//把歌曲加入到播放列表

        i++;
    }

}

void music::pModelclear()
{
    pModel->clear();
}

void music::on_pushButton_clicked()
{
    pModel->clear();
    playlist->clear();
    song_List.clear();
    QString key = ui->lineEdit->text();//记录搜索栏里面的数据
    //将要搜索的数据放入索引内容
    QString url = QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(key);
    manager->get(QNetworkRequest(QUrl(url)));

}

void music::replyFinished(QNetworkReply *reply)
{
    qDebug()<<"网页响应已完成"<<endl;
    QVariant ret = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<"网页返回状态为"<<ret<<endl;
    if(ret == 200)//200说明页面访问成功
    {
        QByteArray data = reply->readAll();//读取所有的网络数据

        parseJson(data);
    }
}

void music::parseJson(QByteArray jsonByte)
{
    QString songname_original2; //歌曲名
    QString singername2;        //歌手
    QString album_name2;        //专辑
    int duration2;          	//时间
    int music_id;               //音乐id
    QJsonParseError json_error;//JSON解析错误对象
    //如果想要从JSON字符串中得到JSON对象以及数组，就需要把JSON字符串转为JSON文档
    QJsonDocument parse_doucment = QJsonDocument::fromJson(jsonByte, &json_error);

    if (json_error.error == QJsonParseError::NoError)//判断解析过程是否有错误
    {
        if (parse_doucment.isObject())//首先判断文档是否是一个json对象
        {
            QJsonObject rootObj = parse_doucment.object();//获取文档JSON对象
            if (rootObj.contains("result"))//第二判断对象中是否包含键result
            {
                QJsonValue valuedata = rootObj.value("result");//获得result对应的值
                if (valuedata.isObject())//第三判断result对应的值是否是一个对象
                {
                    QJsonObject valuedataObject = valuedata.toObject();//把QJsonValue转为JsonObject对象
                    if (valuedataObject.contains("songs"))//第四判断JsonObject对象中包不包含songs
                    {
                        QJsonValue valueArray = valuedataObject.value("songs");//得到songs关键字对应的值
                        {
                            if (valueArray.isArray())//第五判断songs关键字对应的值是不是数组
                            {
                                //把结果转为QJsonArray数组才能遍历
                                QJsonArray array = valueArray.toArray();
                                int size = array.size();//(size>36?36:size)//记录数组的数据个数
                                 for (int i = 0; i <=size; i++)
                                 {
                                     QJsonValue value = array.at(i);
                                     if (value.isObject())//再判断数组第i个元素是不是个对象
                                     {
                                         //把数组的第i个元素变成一个JSON对象
                                         QJsonObject object = value.toObject();
                                         //专辑1
                                         if (object.contains("album"))//判断该对象中是否有album
                                         {
                                              QJsonValue album_Object_1 = object.value("album");//将album用QJsonValue暂存，后续进一步判断
                                              if (album_Object_1.isObject())//判断album是否是一个对象
                                              {
                                                  QJsonObject album_Object_1_tmp=album_Object_1.toObject();//将album变成一个json对象
                                                  if(album_Object_1_tmp.contains("name"))//判断该对象中是否包含name
                                                  {
                                                      QJsonValue ID_value = album_Object_1_tmp.value("name");//将对象中的name赋予ID_value
                                                      if (ID_value.isString())//判断name是不是string类型
                                                      {
                                                          album_name2 = ID_value.toString();//将ID_value转为字符串类型赋予album_name2
                                                      }
                                                  }
                                              }
                                         }
                                         if (object.contains("alias"))//专辑2
                                         {
                                             QJsonValue Album_value_tmp=object.value("alias");//得到alias关键字对应的值，方便后面判断
                                             if (Album_value_tmp.isArray())
                                             {
                                                 //确定是数组后转换为QJsonArray类型方便使用Album_value_array.at(0)
                                                 QJsonArray Album_value_array=Album_value_tmp.toArray();
                                                 if(Album_value_array.at(0).toString()!="")
                                                 {
                                                     album_name2 = Album_value_array.at(0).toString()+"(别名)";
                                                 }
                                             }
                                         }
                                         if (object.contains("artists"))//歌手
                                         {
                                             QJsonValue artists_value_tmp=object.value("artists");
                                             if(artists_value_tmp.isArray())
                                             {
                                                 QJsonArray artists_array=artists_value_tmp.toArray();
                                                 int artists_size = artists_array.size();
                                                 for (int k = 0; k <=artists_size; k++)
                                                 {
                                                     QJsonValue artists_name=artists_array.at(k);
                                                     if(artists_name.isObject())
                                                     {
                                                         QJsonObject artists_name_object=artists_name.toObject();
                                                         if(artists_name_object.contains("name"))
                                                         {
                                                             //take是把对象中的“name”拿出来，这里也可以用vallue
                                                             QJsonValue artistsname=artists_name_object.take("name");
                                                             if (artistsname.isString())
                                                             {
                                                                 if(k==0)//第一个名字
                                                                 {
                                                                     singername2 = artistsname.toString();
                                                                 }
                                                                 else//多个名字加到第一个名字后面
                                                                 {
                                                                     singername2 = singername2 + "/" +artistsname.toString();
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                         if (object.contains("id"))
                                         {
                                             QJsonValue songs_id=object.value("id");
                                             {
                                                 if(!songs_id.isNull())
                                                 {
                                                     music_id=songs_id.toInt();
                                                 }
                                             }
                                         }
                                         if (object.contains("duration"))
                                         {
                                             QJsonValue AlbumID_value = object.take("duration").toInt();
                                             duration2 = AlbumID_value.toInt();
                                             duration2=duration2/1000;
                                             if (object.contains("name"))
                                             {
                                                 QJsonValue songname=object.value("name");
                                                 if(songname.isString())
                                                 {
                                                     songname_original2=songname.toString();
                                                 }
                                             }
                                             song _song;//定义一个歌曲结构体
//                                             _song.album_name = album_name2.toStdString().c_str();
                                             strcpy(_song.album_name,album_name2.toStdString().c_str());
                                             strcpy(_song.singer,singername2.toStdString().c_str());
                                             strcpy(_song.songname,songname_original2.toStdString().c_str());
//                                             _song.singer = singername2;
//                                             _song.songname = songname_original2;
                                             _song.duration2 = duration2;
                                             _song.music_id = music_id;

                                             song_List.push_back(_song);//保存歌曲信息到链表
                                             //构建歌曲播放链接
//                                             playlist->clear();
                                             QString play_url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(music_id);
                                             playlist->addMedia(QUrl(play_url));//把歌曲加入到播放列表
//                                             qDebug()<<playlist->currentIndex()<<endl;
                                         }
                                         //放入表格
                                         pModel->setHorizontalHeaderLabels(titles);
                                         QList<QStandardItem *> sti;
                                         sti<< new QStandardItem(songname_original2)<< new QStandardItem(singername2)<< new QStandardItem(album_name2)<<new QStandardItem(QString().number(duration2))<<new QStandardItem("未收藏");

                                         pModel->appendRow(sti);
                                     }
                                 }
                            }
                        }
                    }
                }
            }
        }
        else
        {
            qDebug() << json_error.errorString();
        }
    }
}

void music::on_tableView_doubleClicked(const QModelIndex &index)
{
    currentIndex=index.row();
    qDebug()<<index.row()<<song_List.at(index.row()).songname<<endl;
    playlist->setCurrentIndex(index.row());//双击的行数就是播放列表中歌曲的下标
    player->play();
    QString str=QString("%1 %2").arg(song_List.at(index.row()).singer).arg(song_List.at(index.row()).songname);
    this->ui->label_2->setText(str);
}

void music::on_tableView_clicked(const QModelIndex &index)
{

    if(index.column() != 4)//如果不是第四列就不要改变
    {
        return;
    }
    QVariant ret = pModel->data(index);//获得索引标识的模型数据,QVariant是任意类型
//    QStandardItem * item = pModel->item(index.row(),index.column());
//    delete item;//释放掉原有的选项
    if(ret == "未收藏")
    {
        //后面这部分代码可能会出错
        qDebug()<<song_List.at(index.row()).singer<<endl;
        QMSG msg;
        msg.type=3;
        song s = song_List.at(index.row());
        qDebug()<<"111111"<<s.singer<<endl;
        memcpy(msg.buf,&s,sizeof(s));
        clientSocket->write((char*)&msg,sizeof(msg));

        //这里new QStandardItem是为了填补QStandardItem *item这个参数
        pModel->setItem(index.row(),index.column(),new QStandardItem("已收藏"));
    }
    else if(ret == "已收藏")
    {
        QMSG msg;
        msg.type=5;
        song s = song_List.at(index.row());
        qDebug()<<"222222"<<s.singer<<endl;
        memcpy(msg.buf,&s,sizeof(s));
        clientSocket->write((char*)&msg,sizeof(msg));
        pModel->setItem(index.row(),index.column(),new QStandardItem("未收藏"));
    }
}
QString formatTime(qint64 time) {
    qint64 seconds = time / 1000;
    qint64 minutes = seconds / 60;
    seconds %= 60;
    return QString("%1:%2")
              .arg(minutes, 2, 10, QChar('0'))
              .arg(seconds, 2, 10, QChar('0'));
}
void music::slot_positionChanged(qint64 position)
{
//    qDebug()<<position<<endl;
    ui->label->setText(formatTime(player->position()) + "/" + formatTime(player->duration()));

    ui->horizontalSlider->setValue(position);
}
void music::slot_durationChanged(qint64 duration)
{
    ui->label->setText(formatTime(player->position()) + "/" + formatTime(player->duration()));

    ui->horizontalSlider->setRange(0,duration);
}
void music::on_horizontalSlider_sliderReleased()
{
    int ret = ui->horizontalSlider->value();//记录滑块松下的位置
    player->setPosition(ret);//从松下的位置开始播放
}

void music::on_listWidget_itemClicked(QListWidgetItem *item)
{

}

void music::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    QString text=current->text();
    if(text=="我喜欢")
    {
        qDebug()<<clientSocket<<endl;
        song_List.clear();
        qDebug()<<"------------"<<endl;
        pModel->clear();
        playlist->clear();

        QMSG msg;
        msg.type=4;
        strcpy(msg.buf,"name");
        qDebug()<<msg.type<<endl;
        clientSocket->write((char*)&msg,sizeof(msg));//1

    }
}

void music::on_pushButton_3_clicked()
{
    if(player->state()==QMediaPlayer::PlayingState)
    {
        player->pause();
        ui->pushButton_3->setStyleSheet("border-image: url(:/播放.png); border:3px solid black; border-radius: 50px; ");
    }
    else
    {
        player->play();
        ui->pushButton_3->setStyleSheet("border-image: url(:/暂停.png); border:3px solid black; border-radius: 50px; ");
    }

}

void music::on_pushButton_2_clicked()
{
    if(playmodel==1)
    {
        if (currentIndex <= 0) {
            currentIndex = playlist->mediaCount()-1; // 跳转到最后一首
            qDebug()<<"111111"<<song_List.at(currentIndex).songname<<endl;
            playlist->setCurrentIndex(currentIndex);
            player->play();
            QString str=QString("%1 %2").arg(song_List.at(currentIndex).songname).arg(song_List.at(currentIndex).singer);
            this->ui->label_2->setText(str);
//            qDebug()<<"111111"<<song_List.at(currentIndex-1).songname<<endl;
//            qDebug()<<playlist->mediaCount()<<song_List.at(currentIndex-1).songname<<endl;
        }
        else
        {
            currentIndex--;
            playlist->setCurrentIndex(currentIndex);
            player->play();
            QString str=QString("%1 %2").arg(song_List.at(currentIndex).songname).arg(song_List.at(currentIndex).singer);
            this->ui->label_2->setText(str);
        }
    }
    else
    {
        if (currentIndex <= 0) {
                    currentIndex = playlist->mediaCount()-1; // 跳转到最后一首
                    qDebug()<<"222222"<<song_List.at(currentIndex).songname<<endl;
                    playlist->setCurrentIndex(currentIndex);
                    player->play();
                    QString str=QString("%1 %2").arg(song_List.at(currentIndex).songname).arg(song_List.at(currentIndex).singer);
                    this->ui->label_2->setText(str);
                }
        else {

            playlist->previous();
            currentIndex=playlist->currentIndex();
            QString str=QString("%1 %2").arg(song_List.at(currentIndex).songname).arg(song_List.at(currentIndex).singer);
            this->ui->label_2->setText(str);
        }
    }



}

void music::on_pushButton_4_clicked()
{

    playlist->next();
    currentIndex=playlist->currentIndex();
    QString str=QString("%1 %2").arg(song_List.at(currentIndex).songname).arg(song_List.at(currentIndex).singer);
    this->ui->label_2->setText(str);

}

void music::on_comboBox_currentIndexChanged(const QString &arg1)
{
    if(ui->comboBox->currentText()=="顺序播放")
    {
        playlist->setPlaybackMode(QMediaPlaylist::Loop);
    }
    if(ui->comboBox->currentText()=="随机播放")
    {
        playlist->setPlaybackMode(QMediaPlaylist::Random);

    }
    if(ui->comboBox->currentText()=="单曲循环")
    {
        playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
}
